/**
 * UninaDocentiSync - A Java application to synchronize Unina resources
 * Copyright (C) 2011  Fabio Scippacercola (nonplay.programmer@gmail.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

package uninadocentisync;

import java.awt.event.WindowEvent;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import uninadocentisync.guibeans.SplashDialog;
import uninadocentisync.guibeans.MainFrame;

/**
 *  Contenitore dell'applicazione, ed inoltre gestore della storyboard
 * dell'interfaccia utente.
 *
 * @author Fabio Scippacercola (nonplay.programmer@gmail.com)
 */
public class Main implements Runnable
{

    public void run() {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e)
        {}

        FileHandler h = null;
        try
        {
            try
            {
                h = new FileHandler("log.xml");
                ApplicationUtils.getInstance().addHandler(h);

                Handler swingHandler = new Handler() {
                    @Override
                    public void close() throws SecurityException {}

                    @Override
                    public void flush() {}

                    @Override
                    public void publish(final LogRecord lr) {
                        if (lr.getLevel() == Level.WARNING || lr.getLevel() == Level.SEVERE)
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    javax.swing.JOptionPane.showMessageDialog(null, String.format("%s\n%s", lr.getMessage(), (lr.getThrown() != null ? lr.getThrown().getMessage() : "")),
                                            (lr.getLevel() == Level.WARNING ? "Attenzione!" : "Errore!"),
                                            (lr.getLevel() == Level.WARNING ? javax.swing.JOptionPane.WARNING_MESSAGE : javax.swing.JOptionPane.ERROR_MESSAGE));
                                }
                            });
                    }
                };
                ApplicationUtils.getInstance().addHandler(swingHandler);
            }
            catch (Exception e)
            {
                ApplicationUtils.getInstance().log(Level.WARNING, "Errore nell'aggiungere un file handler al logger!", e);
                h = null;
            }

            // Mostra Splashdialog bloccando
            SplashDialog.showModalSplashDialog();

            // Mostra mainWindow e attende la chiusura dell'applicazione
            final java.util.concurrent.CountDownLatch b = new java.util.concurrent.CountDownLatch(1);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    final MainFrame f = new MainFrame();
                    f.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosed(WindowEvent we) {
                            b.countDown();
                        }
                    });
                    f.setVisible(true);
                }
            });
            b.await(); // Attendi chiusura finestra principale

            // Prima chiudere salvo le proprietà
            ApplicationUtils.getInstance().savePropsOnFile();
        }
        catch (Exception e)
        {
            ApplicationUtils.getInstance().log(Level.SEVERE, "Errore nell'esecuzione dell'applicazione!", e);
        }
        finally
        {
            if (h != null)
            {
                ApplicationUtils.getInstance().removeHandler(h);
                h.close();
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        if (args.length > 0 && args[0].equals("--debug"))
        {            
            java.util.logging.Handler h = new java.util.logging.ConsoleHandler();
            h.setLevel(Level.ALL);
            ApplicationUtils.getInstance().addHandler(h);
            ApplicationUtils.getInstance().setDebuggingEnabled(true);
            ApplicationUtils.getInstance().log(Level.FINEST, "Debug mode started!", null);
        }

        new Main().run();
    }

}
